package org.study.plus.boot.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.*;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 作用描述
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2023年05月06日
 */
@Slf4j
@Configuration
@MapperScan(basePackages = {"org.study.plus.boot.mapper"})
public class MyBatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        // MybatisPlus 插件，参考 https://www.baomidou.com/pages/2976a3/#mybatisplusinterceptor
        // 使用多个功能时特别注意顺序，建议使用顺序为：多租户、动态表名；分页、乐观锁；sql性能规范、防止全表更新与删除。总结即：对sql进行单次改造的优先放入，不对sql进行改造的最后放入
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        // 1、多租户插件TenantLineInnerInterceptor，在Mapper接口的方法上使用@InterceptorIgnore(tenantLine = "true")可以排除租户条件
        //interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new MyTenantLineHandler()));

        // 2、动态表名插件DynamicTableNameInnerInterceptor
        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        dynamicTableNameInnerInterceptor.setTableNameHandler(new MyTableNameHandler());
        interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);

        // 3、自动分页插件PaginationInnerInterceptor
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));

        // 4、乐观锁插件OptimisticLockerInnerInterceptor
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());

        // 5、SQL性能规范插件
        //interceptor.addInnerInterceptor(new IllegalSQLInnerInterceptor());

        // 6、防止全表更新与删除插件
        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
        return interceptor;
    }
}
